package com.hongxun.design.activitys;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.utils.httputil.HttpStringUtil;

/**
 * Created by zerdoor_pc on 2016/5/14.
 * 展示大图的Activity
 */
public class ShowBigImageActivity extends BaseActivity {
    String path;
    ImageView image;
    Bitmap bitmap;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {

                image.setImageBitmap(bitmap); //设置Bitmap
            }catch (Exception e){}
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showbigimage);
        path = getIntent().getExtras().getString(MString.PATH);
        image = (ImageView) findViewById(R.id.big_image);
//      image.setImageURI(UriUtil.getUri(path));
//      image.setImageBitmap(getHttpBitmap(HttpStringUtil.HeadSpeech + "/" + path));
        image.setOnTouchListener(new TouchListener(image, this));
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //MyLog.L("返回返回返回");
                onBackPressed();
            }
        });
        LoadImage();
    }


    private void LoadImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (MyApp.isOnLine) {
                    bitmap = getHttpBitmap(HttpStringUtil.HeadSpeech + "/" + path);
                } else if (path.contains(MyApp.File.getCachaPath())){
                    try {
                        bitmap = BitmapFactory.decodeFile(path);
                    }catch (Exception e){

                    }
                }else{
                    bitmap = getHttpBitmap(HttpStringUtil.HeadSpeech + "/" + path);
                }
                if (bitmap==null){
                    try {
                        bitmap = BitmapFactory.decodeFile(path);
                    }catch (Exception e){
                    }
                }
                if (bitmap==null){
                    try {
                        bitmap = getHttpBitmap(path);
                    }catch (Exception e){
                    }
                }
                //从网上取图片
                handler.sendEmptyMessage(2);
                MyLog.L("HTTP_ :" + bitmap+" path="+path);
            }
        }).start();

    }

    /**
     * 从服务器取图片
     *
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setConnectTimeout(0);
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取网落图片资源
     *
     * @param url
     * @return
     */
    public static Bitmap getHttBitmap(String url) {
        URL myFileURL;
        Bitmap bitmap = null;
        try {
            myFileURL = new URL(url);
            //获得连接
            HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
            //设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            //连接设置获得数据流
            conn.setDoInput(true);
            //不使用缓存
            conn.setUseCaches(false);
            //这句可有可无，没有影响
            //conn.connect();
            //得到数据流
            InputStream is = conn.getInputStream();
            //解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            //关闭数据流
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }


    private final class TouchListener implements OnTouchListener {
        private ImageView imageView;
        Context contextl;

        TouchListener(ImageView imageView, Context context) {
            this.imageView = imageView;
            this.contextl = context;
        }

        /**
         * 记录是拖拉照片模式还是放大缩小照片模式
         */
        private int mode = 0;// 初始状态
        /**
         * 拖拉照片模式
         */
        private static final int MODE_DRAG = 1;
        /**
         * 放大缩小照片模式
         */
        private static final int MODE_ZOOM = 2;

        /**
         * 用于记录开始时候的坐标位置
         */
        private PointF startPoint = new PointF();
        /**
         * 用于记录拖拉图片移动的坐标位置
         */
        private Matrix matrix = new Matrix();
        /**
         * 用于记录图片要进行拖拉时候的坐标位置
         */
        private Matrix currentMatrix = new Matrix();

        /**
         * 两个手指的开始距离
         */
        private float startDis;
        /**
         * 两个手指的中间点
         */
        private PointF midPoint;


        @Override
        public boolean onTouch(View v, MotionEvent event) {
            /** 通过与运算保留最后八位 MotionEvent.ACTION_MASK = 255 */
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                // 手指压下屏幕
                case MotionEvent.ACTION_DOWN:
                    mode = MODE_DRAG;

                    // 记录ImageView当前的移动位置
                    currentMatrix.set(imageView.getImageMatrix());
                    startPoint.set(event.getX(), event.getY());
                    break;
                // 手指在屏幕上移动，改事件会被不断触发
                case MotionEvent.ACTION_MOVE:
                    // 拖拉图片

                    if (mode == MODE_DRAG) {
                        float dx = event.getX() - startPoint.x; // 得到x轴的移动距离
                        float dy = event.getY() - startPoint.y; // 得到x轴的移动距离
                        // 在没有移动之前的位置上进行移动
                        matrix.set(currentMatrix);
                        matrix.postTranslate(dx, dy);
                    }
                    // 放大缩小图片
                    else if (mode == MODE_ZOOM) {
                        float endDis = distance(event);// 结束距离
                        if (endDis > 10f) { // 两个手指并拢在一起的时候像素大于10
                            float scale = endDis / startDis;// 得到缩放倍数
                            matrix.set(currentMatrix);
                            matrix.postScale(scale, scale, midPoint.x, midPoint.y);
                        }
                    }
                    break;
                // 手指离开屏幕
                case MotionEvent.ACTION_UP:
                    // 当触点离开屏幕，但是屏幕上还有触点(手指)
//                    if (event.getEventTime()-event.getDownTime()<100) {
//                        MyLog.L("返回返回返回 false");
//                        ((Activity)contextl).onTouchEvent(event);
//
//                    }
                case MotionEvent.ACTION_POINTER_UP:
                    mode = 0;
                    break;
                // 当屏幕上已经有触点(手指)，再有一个触点压下屏幕
                case MotionEvent.ACTION_POINTER_DOWN:
                    mode = MODE_ZOOM;

                    /** 计算两个手指间的距离 */
                    startDis = distance(event);
                    /** 计算两个手指间的中间点 */
                    if (startDis > 10f) { // 两个手指并拢在一起的时候像素大于10
                        midPoint = mid(event);
                        //记录当前ImageView的缩放倍数
                        currentMatrix.set(imageView.getImageMatrix());
                    }
                    break;
            }
            imageView.setImageMatrix(matrix);
            return event.getEventTime() - event.getDownTime() > 300;
        }

        /**
         * 计算两个手指间的距离
         */
        private float distance(MotionEvent event) {
            float dx = event.getX(1) - event.getX(0);
            float dy = event.getY(1) - event.getY(0);
            double sqrt = Math.sqrt(dx * dx + dy * dy);
            /** 使用勾股定理返回两点之间的距离 */
//            return FloatMath.sqrt(dx * dx + dy * dy);
            return Float.valueOf(String.valueOf(sqrt));
        }

        /**
         * 计算两个手指间的中间点
         */
        private PointF mid(MotionEvent event) {
            float midX = (event.getX(1) + event.getX(0)) / 2;
            float midY = (event.getY(1) + event.getY(0)) / 2;
            return new PointF(midX, midY);
        }

    }

    @Override
    protected void onDestroy() {
        image = null;
        if (bitmap != null) bitmap.recycle();
        super.onDestroy();
    }
}
